package boun.center;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class CalendarEventComparator implements Comparator<CalendarEvent>{
	 
    @Override
    public int compare(CalendarEvent o1, CalendarEvent o2) {
    	int res = o1.getBeginDate().compareTo(o2.getBeginDate());
        return res == 0 ? 0 : o1.getEndDate().compareTo(o2.getEndDate());
    }
}

public class CalendarFetcher {
	
	public ArrayList<CalendarEvent> fetchCalendar() throws IOException {
		String res = WebDownloader.fetchWebContent("http://www.boun.edu.tr/en-US/Content/Academic/Academic_Calendar/2011_Academic_Calendar.aspx");
		ArrayList<CalendarEvent> calendarEvents = getEvents(res);
		Collections.sort(calendarEvents, new CalendarEventComparator());
		return calendarEvents;
	}
	
	private ArrayList<CalendarEvent> getEvents(String content) {
		Pattern rowPattern = Pattern.compile("<td class=\"table1TableEvenCol\">(.*?)</td>");
		Matcher matcher = rowPattern.matcher(content);
		CalendarEvent lastEvent = null;
		ArrayList<CalendarEvent> result = new ArrayList<CalendarEvent>();
		boolean isFirst = true;
		while (matcher.find()) {
			String curRow = matcher.group(1).trim().replaceAll("&nbsp;", "");
			if (isHeader(curRow)) {
				if (!isFirst) {
					result.add(lastEvent);
				}
				lastEvent = new CalendarEvent();
				lastEvent.setDates(getDateDurationString(curRow));
				isFirst = false;
			} else {
				curRow = curRow.replaceAll("<br />", "\n").trim();
				if (curRow.compareTo("") != 0) {
					lastEvent.addDescription(curRow);
				}
			}
		}
		result.add(lastEvent);
		return result;
	}
	
	private String getDateDurationString(String str) {
		Pattern dateDurationPattern = Pattern.compile("\\d[\\d+\\.\\-]{5,}\\d");
		Matcher matcher = dateDurationPattern.matcher(str);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}
	
	private boolean isHeader(String str) {
		return str.startsWith("<span class=\"bold\">");
	}

}